const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
const { ethers } = require("hardhat");

if (isMainThread) {
    // 这是主线程
    console.log('Main thread is running');

    // 创建多个工作线程，并传递不同的任务数据

    // 监听帮助者加入
    const worker1 = new Worker(__filename, {
        workerData: { task: 'task1', message: 'Listen for helpers to join the project' }
    });

    // 分配任务
    const worker2 = new Worker(__filename, {
        workerData: { task: 'task2', message: 'Assign tasks to helpers' }
    });

    // 评估任务
    const worker3 = new Worker(__filename, {
        workerData: { task: 'task3', message: 'Evaluate the task' }
    })

    // 统一的事件监听函数
    function setupWorkerListeners(worker) {
        worker.on('message', (message) => {
            console.log(`Received message from worker: ${message}`);
        });

        worker.on('error', (error) => {
            console.error(`Worker error: ${error}`);
        });

        worker.on('exit', (code) => {
            if (code !== 0) {
                console.error(`Worker stopped with exit code ${code}`);
            }
        });
    }

    // 设置多个工作线程的事件监听
    [worker1, worker2, worker3].forEach(setupWorkerListeners);
} else {
    // 这是工作线程
    console.log('Worker thread is running');

    // 获取主线程传递的数据
    const { task, message } = workerData;
    console.log(`Received message from main thread: ${message}`);

    // 根据任务类型执行不同的任务
    if (task === 'task1') {
        while (1)
        {
            
        }
    } else if (task === 'task2') {

    } else if (task === 'task3') {

    }
}